<template>
  <div class="record-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="record-tabs">
      <el-tab-pane label="未创建入驻流程" name="0"></el-tab-pane>
      <el-tab-pane label="备案" name="1"></el-tab-pane>
      <el-tab-pane label="合同" name="2"></el-tab-pane>
      <el-tab-pane label="物业/办证" name="3"></el-tab-pane>
      <el-tab-pane label="入驻告知" name="4"></el-tab-pane>
    </el-tabs>
    <el-card class="filter-card">
      <el-form
        :inline="true"
        :model="queryParams"
        label-width="100px"
        class="filter-form"
      >
        <el-form-item label="载体" prop="zt">
          <el-select
            v-model="queryParams.zt"
            placeholder="请选择载体"
            clearable
            style="width: 200px"
          >
            <el-option label="联健元和" value="联健元和" />
            <el-option label="达博" value="达博" />
            <el-option label="科澜项目" value="科澜项目" />
            <el-option label="国科项目" value="国科项目" />
            <el-option label="黄埭项目" value="黄埭项目" />
            <el-option label="金扶梯" value="金扶梯" />
            <el-option label="北联新翼" value="北联新翼" />
            <el-option label="深圳项目" value="深圳项目" />
            <el-option label="西山项目" value="西山项目" />
            <el-option label="秦淮项目" value="秦淮项目" />
            <el-option label="双创中心" value="双创中心" />
            <el-option label="创界项目" value="创界项目" />
            <el-option label="江环项目" value="江环项目" />
            <el-option label="江北项目" value="江北项目" />
            <el-option label="拓展项目" value="拓展项目" />
            <el-option label="试点项目" value="试点项目" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业名称" prop="companyName">
          <el-input
            v-model="queryParams.companyName"
            placeholder="请输入企业名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入驻类型">
          <el-select
            v-model="queryParams.entryMode"
            placeholder="请选择入驻类型"
            clearable
            style="width: 200px"
          >
            <el-option label="实体企业" value="实体" />
            <el-option label="挂靠企业" value="挂靠" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="list-card" style="margin-top: 18px">
      <el-table v-loading="loading" :data="companyList" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="80" align="left" />
        <el-table-column prop="zt" label="载体" min-width="120" align="left" />
        <el-table-column
          prop="companyName"
          label="企业名称"
          width="300"
          align="left"
          show-overflow-tooltip
        />
        <!-- <el-table-column prop="registeredCapital" label="注册资金(万)" min-width="140" />
        <el-table-column
          prop="estimatedTaxRevenue"
          label="预计税收(万)"
          min-width="140"
        /> -->
        <el-table-column prop="entryMode" label="入驻方式" min-width="100" align="left" />
        <el-table-column
          prop="industryCategory"
          label="行业分类"
          min-width="200"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column prop="merchants" label="招商员" min-width="100" align="left" />
        <el-table-column
          prop="companyClass"
          label="注册类型"
          min-width="100"
          align="left"
        />
        <el-table-column
          prop="roomNum"
          label="房间号"
          min-width="80"
          width="200"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          prop="startTime"
          label="接收日期"
          min-width="140"
          :formatter="dateOnlyFormatter"
          align="left"
        />
        <!-- <el-table-column
          prop="endTime"
          label="办结日期"
          min-width="140"
          :formatter="dateOnlyFormatter"
        /> -->
        <el-table-column label="操作" min-width="240" fixed="right" align="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewCompanyProfile(row)">
              查看企业档案 </el-button
            ><el-button type="primary" link v-if="row.status" @click="openDialog(row)"
              >入驻资料</el-button
            >
            <el-button type="primary" link v-else @click="handleCreateProcess(row)"
              >创建入驻流程</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();

import {
  getCompanyListpage,
  createProcess,
  submitAndUpdate,
} from "@/api/company/index.js";
import { insertCertification, createFeiShuApprovalTask } from "@/api/company/info.js";
// 只保留日期部分
function dateOnlyFormatter(row, column, cellValue) {
  if (!cellValue) return "";
  // 支持2023-09-09 12:00:00或2023-09-09T12:00:00Z等
  return String(cellValue).split(" ")[0].split("T")[0];
}
const loading = ref(false);
const total = ref(0);
const companyList = ref([]);
const activeTab = ref("0");
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  companyName: "",
  zt: "",
  entryMode: "",

  status: 0,
});
import { useRouter } from "vue-router";
const router = useRouter();
function openDialog(row) {
  // 跳转前参数校验，防止companyId等为undefined导致路由报错
  if (!row.companyId) {
    proxy.$modal.msgWarning("缺少companyId，无法跳转") ||
      alert("缺少companyId，无法跳转");
    return;
  }
  if (row.entryMode == "实体") {
    router.push({
      path: "/companyStep",
      query: {
        companyId: row.companyId,
        companyStatus: row.status || "",
        entryMode: row.entryMode || "",
        companyClass: row.companyClass || "",
        companyName: row.companyName || "",
        zt: row.zt || "",
        type: "Operation",
        carrieType: row.carrieType || "",
      },
    });
  } else if (row.entryMode == "挂靠") {
    router.push({
      path: "/companyStepVirtual",
      query: {
        companyId: row.companyId,
        companyStatus: row.status || "",
        entryMode: row.entryMode || "",
        companyClass: row.companyClass || "",
        companyName: row.companyName || "",
        zt: row.zt || "",
        type: "Operation",
      },
    });
  }
}

// 获取企业列表
function getList() {
  loading.value = true;
  console.log("queryParams", queryParams);

  getCompanyListpage(queryParams)
    .then((res) => {
      const result = res;
      if (result && result.code === 200) {
        // 防御性处理，确保rows为数组
        let rows = [];
        if (Array.isArray(result.rows)) {
          rows = result.rows;
        } else if (
          result.rows &&
          typeof result.rows === "object" &&
          typeof result.rows.length === "number"
        ) {
          rows = Array.from(result.rows);
        }
        companyList.value = rows;
        total.value = result.total || 0;
      } else {
        companyList.value = [];
        total.value = 0;
      }
    })
    .catch(() => {
      companyList.value = [];
      total.value = 0;
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false;
      }, 300);
    });
}

function handleTabChange(tab) {
  queryParams.status = Number(tab.paneName);
  queryParams.pageNum = 1;
  getList();
}
function handleCreateProcess(row) {
  loading.value = true;
  if (row.zt == "江环项目" || row.zt == "秦淮项目" || row.entryMode == "实体不注册") {
    createProcess({ companyId: row.companyId })
      .then((res) => {
        if (res.code === 200) {
          insertCertification({ companyId: row.companyId });
          submitAndUpdate({ companyId: row.companyId, status: 2 });
          proxy.$modal.msgSuccess("流程创建成功");
          // 切换到备案tab页
          activeTab.value = "2";
          handleTabChange({ paneName: "2" });
        } else {
          proxy.$modal.msgError(res.msg || "流程创建失败") ||
            alert(res.msg || "流程创建失败");
        }
      })
      .catch((err) => {
        console.error("流程创建失败:", err);
      })
      .finally(() => {
        loading.value = false;
      });
  } else {
    createProcess({ companyId: row.companyId })
      .then((res) => {
        if (res.code === 200) {
          insertCertification({ companyId: row.companyId });
          proxy.$modal.msgSuccess("流程创建成功");
          // 切换到备案tab页
          activeTab.value = "1";
          handleTabChange({ paneName: "1" });
        } else {
          proxy.$modal.msgError(res.msg || "流程创建失败") ||
            alert(res.msg || "流程创建失败");
        }
      })
      .catch((err) => {
        console.error("流程创建失败:", err);
      })
      .finally(() => {
        loading.value = false;
      });
  }
}
// 查看企业档案
const viewCompanyProfile = (row) => {
  console.log("viewCompanyProfile companyId:", row.companyId);
  router.push({
    path: "/lookCompany",
    query: { companyId: row.companyId },
  });
};

onMounted(() => {
  getList();
});

function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

function resetQuery() {
  queryParams.companyName = "";
  queryParams.zt = "";
  queryParams.entryMode = "";
  queryParams.pageNum = 1;
  getList();
}
</script>

<style scoped>
.record-container {
  padding: 24px 32px 0 32px;
  /* background: #f4f6fa; */
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 12px;
  /* background: #fff; */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.filter-form {
  padding: 8px 0 0 0;
}

.list-card {
  margin-bottom: 18px;
  /* background: #fff; */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #f0f0f0;
}

.el-table {
  /* background: #fff; */
  border-radius: 8px;
  font-size: 15px;
}

.el-table th {
  /* background: #fff; */
  color: #333;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.el-table td {
  color: #444;
  border-bottom: 1px solid #f0f0f0;
}

.el-button[type="primary"] {
  background: linear-gradient(90deg, #4f8cff 0%, #38c8fa 100%);
  border: none;
  color: #fff;
  border-radius: 6px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(32, 159, 240, 0.08);
  transition: background 0.2s;
}

.el-button[type="primary"]:hover {
  background: linear-gradient(90deg, #2563eb 0%, #38c8fa 100%);
}

.el-dialog {
  border-radius: 10px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
}

.el-dialog__header {
  /* background: #fff; */
  border-radius: 10px 10px 0 0;
  font-size: 18px;
  font-weight: 600;
  color: #2563eb;
}

.el-dialog__body {
  /* background: #fff; */
  padding: 28px 36px 18px 36px;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.dialog-form {
  margin-top: 0;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-form-item .el-link {
  font-size: 15px;
}

.el-form-item .el-upload {
  margin-top: 0;
}

.el-dialog__footer {
  /* background: #fff; */
  border-radius: 0 0 10px 10px;
  padding: 12px 32px;
}

.el-upload {
  margin-top: 12px;
}

.el-link {
  font-size: 15px;
}

.el-alert {
  margin-bottom: 8px;
}
</style>
